<?php

declare(strict_types=1);

namespace app;

use think\facade\Env;
use think\cache\driver\Redis;
use app\model\baseInfo\{
  EverydayPhrases as EverydayPhrasesModel,
  SiteInfo as SiteInfoModel,
  NavMenu as NavMenuModel,
  FriendShip as FriendlyLinkModel,
};

/**
 * 基本信息控制器
 */
class BaseInfoController
{

  // Redis初始化
  protected static function redisInit()
  {
    $redis = new Redis();
    $redis->connect(Env::get('redis.hostname', '127.0.0.1'), Env::get('redis.port', 3306));
    $redis->auth(Env::get('redis.password', ''));
    $redis->select(Env::get('redis.select', 0));
    return $redis;
  }
  ######################################################################################################################










  ######################################################################################################################
  # 网站基本信息
  ######################################################################################################################

  // 获取网站基本信息
  public static function siteInfo()
  {
    $result = self::redisInit()->get('baseinfo_siteinfo');
    if ($result) {
      return $result;
    } else {
      $data = SiteInfoModel::column('option_value', 'option_name');
      self::redisInit()->set('baseinfo_siteinfo', $data, 60 * 60 * 24);
      return $data;
    }
  }
  ######################################################################################################################










  ######################################################################################################################
  # 友情链接
  ######################################################################################################################

  // 获取友情链接
  public static function friendlyLink()
  {
    $result = self::redisInit()->get('baseinfo_friendlylink');
    if ($result) {
      return $result;
    } else {
      $data = FriendlyLinkModel::field('name, url')->order('link_order desc')->select()->toArray();
      self::redisInit()->set('baseinfo_friendlylink', $data, 60 * 60 * 24);
      return $data;
    }
  }
  ######################################################################################################################





  ######################################################################################################################
  # 分类栏目信息
  ######################################################################################################################

  // 获取网站专栏信息
  public static function websiteCategory()
  {
    $result = self::redisInit()->get('baseinfo_website_category');
    if ($result) {
      return $result;
    } else {
      $list = config('contenthelper.Category');
      $name = array_column(config('contenthelper.Category'), 'name', 'id');
      $data = compact('list', 'name');
      self::redisInit()->set('baseinfo_website_category', $data, 60 * 60 * 24);
      return $data;
    }
  }
  ######################################################################################################################









  ######################################################################################################################
  # 网站主导航和副导航
  ######################################################################################################################

  // 获取网站主导航
  public static function mainNavMenu()
  {
    $result = self::redisInit()->get('baseinfo_main_nav_menu');
    if ($result) {
      return $result;
    } else {
      $controller = new self;
      $data = $controller->getMainNavMenu();
      self::redisInit()->set('baseinfo_main_nav_menu', $data, 60 * 60 * 24);
      return $data;
    }
  }

  // 获取网站副导航
  public static function viceNavMenu()
  {
    $result = self::redisInit()->get('baseinfo_vice_nav_menu');
    if ($result) {
      return $result;
    } else {
      $controller = new self;
      $data = $controller->getViceNavMenu();
      self::redisInit()->set('baseinfo_vice_nav_menu', $data, 60 * 60 * 24);
      return $data;
    }
  }

  /**
   * 获取网站主导航
   * @access public
   * @param  数据表 pub_nav_menu
   * @return array
   */
  protected function getMainNavMenu()
  {
    $first_menu = NavMenuModel::where('parent_id', '0')->order('list_order asc')->where('status', 1)->select()->toArray();
    $secon_menu = NavMenuModel::where('parent_id', '<>', '0')->order('list_order asc')->where('status', 1)->select()->toArray();
    foreach ($first_menu as $key => $value) {
      $value['target'] == 1 ? $first_menu[$key]['tg'] = 'target="_blank"' : $first_menu[$key]['tg'] = '';
      foreach ($secon_menu as $k => $vol) {
        if ($vol['parent_id'] == $value['id']) {
          $first_menu[$key]['zclass'][$k] = $vol;
          unset($secon_menu[$k]);
          $vol['target'] == 1 ? $first_menu[$key]['zclass'][$k]['tg'] = 'target="_blank"' : $first_menu[$key]['zclass'][$k]['tg'] = '';
        }
      }
    }
    return $first_menu;
  }

  /**
   * 获取网站副导航
   * @access public
   * @param  数据表 pub_nav_menu
   * @return array
   */
  protected function getViceNavMenu()
  {
    $first_menu = NavMenuModel::where('parent_id', '0')->order('list_order asc')->where('status', 2)->select()->toArray();
    $secon_menu = NavMenuModel::where('parent_id', '<>', '0')->order('list_order asc')->where('status', 2)->select()->toArray();
    foreach ($first_menu as $key => $value) {
      $value['target'] == 1 ? $first_menu[$key]['tg'] = 'target="_blank"' : $first_menu[$key]['tg'] = '';
      foreach ($secon_menu as $k => $vol) {
        if ($vol['parent_id'] == $value['id']) {
          $first_menu[$key]['zclass'][$k] = $vol;
          unset($secon_menu[$k]);
          $vol['target'] == 1 ? $first_menu[$key]['zclass'][$k]['tg'] = 'target="_blank"' : $first_menu[$key]['zclass'][$k]['tg'] = '';
        }
      }
    }
    return $first_menu;
  }
  ######################################################################################################################










  ######################################################################################################################
  # 每日一句
  ######################################################################################################################

  // 获取每日一句
  public static function everydayPhrases()
  {
    $result = self::redisInit()->get('baseinfo_everydayphrases_' . date('Ymd', time()));
    if ($result) {
      return $result;
    } else {
      $controller = new self;
      return $controller->getCalendarPhrases();
    }
  }

  # 天行数据每日一句
  protected function getCalendarPhrases()
  {
    # 获取每日一句信息
    $getphrases = EverydayPhrasesModel::field('thisday, content, note, date')->whereTime('date', 'today')->find();
    if (!$getphrases) {
      $result = $this->postCalendarPhrases();
      if (!$result) return false;
      $dateTime = $result['date'];
      unset($result['date']);
    } else {
      $result['dt'] = $getphrases['thisday'];
      $result['co'] = $getphrases['content'] . '<br />' . $getphrases['note'];
      $dateTime = $getphrases['date'];
    }

    self::redisInit()->set('baseinfo_everydayphrases_' . date('Ymd', $dateTime), $result, 60 * 60 * 24);

    return $result;
  }

  // 远程post获取今天的天行数据每日一句
  protected function postCalendarPhrases()
  {
    $post_data = array('key' => '777e85a44ea15e4d8b08d704e265aeba');
    $postdata = http_build_query($post_data);
    $options = array(
      'http' => array(
        'method' => 'POST',
        'header' => 'Content-type:application/x-www-form-urlencoded',
        'content' => $postdata,
        'timeout' => 1 // 超时时间（单位:s）
      )
    );
    $context = stream_context_create($options);
    $returns = file_get_contents('http://api.tianapi.com/txapi/everyday/index', false, $context);
    $returns = json_decode($returns);
    if ($returns->msg == 'success') {
      $returns = $returns->newslist;
      $returns = $returns[0];
      $result['content'] = $returns->content;
      $result['note']    = $returns->note;
      $result['tts']     = $returns->tts;
      $result['imgurl']  = $returns->imgurl;
      $result['date']    = strtotime($returns->date);
      $result['type']    = 'tianxing';
      $weekarray = array("日", "一", "二", "三", "四", "五", "六");
      $result['thisday'] = date('Y年m月d日', $result['date']) . ' 星期' . $weekarray[date("w", $result['date'])];
      EverydayPhrasesModel::insert($result);
      return ['dt' => $result['thisday'], 'co' => $result['content'] . '<br />' . $result['note'], 'date' => $result['date']];
    } else {
      return false;
    }
  }
  ######################################################################################################################





}
